package dao;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

@Transactional
public abstract class BaseDAO<T, PK extends Serializable> implements IBaseDAO {

    @Resource
    protected SessionFactory sessionFactory;

    protected abstract Class<T> getReferenceClass();

    protected Session getCurrentSession() {
        return this.sessionFactory.getCurrentSession();
    }

    @Override
    public void add(Object entity) {
        getCurrentSession().persist(entity);
    }

    @Override
    public void delete(Object entity) {
        getCurrentSession().delete(entity);
    }

    @Override
    public void delete(Serializable serializable) {
        getCurrentSession().delete(getById(serializable));
    }

    @Override
    public void update(Object entity) {
        getCurrentSession().update(entity);
    }

    @Override
    public void executeSql(String sql) {
        getCurrentSession().createQuery(sql).executeUpdate();
    }

    @Override
    public Object getById(Serializable serializable) {
        return getCurrentSession().get(getReferenceClass(), serializable);
    }

    @Override
    public List getByField(String field, String value) {
        StringBuffer sb = new StringBuffer();
        sb.append("from ").append(this.getReferenceClass().getName()).append(" where ").append(field).append("='")
                .append(value).append("'");
        Query query = getCurrentSession().createQuery(sb.toString());
        return query.list();
    }

    @Override
    public List getViaHql(String hql) {
        return getCurrentSession().createQuery(hql).list();
    }

    @Override
    public List getViaSql(String sql) {
        return null;
    }

    @Override
    public List getAll() {
        StringBuffer sb = new StringBuffer();
        sb.append("from ").append(this.getReferenceClass().getName()).append(" where 1=1");
        Query query = getCurrentSession().createQuery(sb.toString());
        return query.list();
    }
}
